const app = getApp()
// const DBUtil = require('../lib/DBUtil')
const { UrlConfig, PATH, ACTION, DB } = require('./url')
const { cache_load, cache_save } = require('../lib/cache')

const CONFIG_NAME = 'config'
const FILE_NAME = UrlConfig[CONFIG_NAME][PATH]  //云函数文件名

/**
 * [CLOUD] 获取当前小程序 state
 */
function getConfig () {
  let action = UrlConfig[CONFIG_NAME][ACTION]['getConfig']
  return new Promise((resolve, reject) => {
    var cacheData = cache_load('config')
    if (cacheData) {
      return resolve(cacheData)
    }
    app.http(FILE_NAME, { action }).then(res => {
      cache_save('config', res, 86400000) //缓存24小时
      resolve(res)
    }, err => {
      reject(err)
    })
  })

}

/**
 * [CLOUD] 获取广告数据
 */
function getAds() {
  let action = UrlConfig[CONFIG_NAME][ACTION]['getAds']
  return new Promise((resolve, reject) => {
    var cacheData = cache_load('ads')
    if (cacheData) {
      return resolve(cacheData)
    }
    app.http(FILE_NAME, { action }).then(res => {
      cache_save('ads', res, 86400000) //缓存24小时
      resolve(res)
    }, err => {
      reject(err)
    })
  })
}

/**
 * [CLOUD] 获取自定义html
 */
function getHtml() {
  let options = {
    loading: '加载中...'
  }
  let action = UrlConfig[CONFIG_NAME][ACTION]['getHtml']
  return new Promise((resolve, reject) => {
    let cacheData = cache_load('aboutHtml');
    if (cacheData) {
      return resolve(cacheData)
    }
    app.http(FILE_NAME, { action }, options).then(res => {
      cache_save('aboutHtml', res, 86400000) //缓存24小时
      resolve(res)
    }, err => {
      reject(err)
    })
  })
}

module.exports = {
  getConfig,
  getAds,
  getHtml
}